package com.lry.filter.server;

import com.lry.common.CommonConstants;
import com.lry.exception.BizException;
import com.lry.protocol.RpcInvocation;
import com.lry.protocol.RpcMessage;
import com.lry.rpc.config.RpcServiceBean;
import com.lry.rpc.netty.server.ServerCache;
import com.lry.spi.LoadLevel;
import com.lry.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@LoadLevel(name = "token")
@Slf4j
public class ServerTokenFilter implements ServerFilter {

    @Override
    public void filter(RpcMessage rpcMessage) {
        if(rpcMessage.getBody() instanceof RpcInvocation) {
            RpcInvocation rpcInvocation = (RpcInvocation) rpcMessage.getBody();
            RpcServiceBean rpcServiceBean = ServerCache.getService(rpcInvocation);
            String token = rpcMessage.getHead(CommonConstants.TOKEN);
            log.info("收到客户端token="+token);

            if(StringUtils.isNotBlank(rpcServiceBean.getToken())){
                if(!rpcServiceBean.getToken().equals(token)){
                    log.error("token校验失败");
                    throw new BizException("token校验失败");
                }
            }
        }
    }
}
